package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;
import static com.hmdp.utils.RedisConstants.SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询所有商铺类型
     * @return
     */
    @Override
    public Result queryList() {
        //1. 查询缓存
        List<String> stringJSONList = stringRedisTemplate.opsForList().range(SHOP_TYPE_KEY, 0, -1);

        //2. 判断是否存在
        if(CollUtil.isNotEmpty(stringJSONList)){
            //2.1 转换成实体列表
            List<ShopType> shopTypeList = new ArrayList<>();
            for (String str : stringJSONList) {
                ShopType shopType = JSONUtil.toBean(str, ShopType.class);
                shopTypeList.add(shopType);
            }
            return Result.ok(shopTypeList);
        }

        //3. 未命中，查询数据库
        List<ShopType> shopTypeList = list();

        //4. 判断是否存在
        if(CollUtil.isEmpty(shopTypeList)){
            return Result.fail("未查询到商铺类型");
        }

        //5. 存在，写入缓存
        //5.1 转成JSON类型
        List<String> shopTypeJSONList = new ArrayList<>();
        for (ShopType shopType : shopTypeList) {
            shopTypeJSONList.add(JSONUtil.toJsonStr(shopType));
        }

        stringRedisTemplate.opsForList().rightPushAll(SHOP_TYPE_KEY,shopTypeJSONList);

        //6. 返回所有类型
        return Result.ok(shopTypeList);
    }
}
